# uvicorn web:app --reload

from typing import Optional
from fastapi import FastAPI, Form, HTTPException, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import FileResponse

from pydantic import BaseModel
from Migrate import convertXml2Dict  
import os

import uvicorn

app = FastAPI()


app.mount("/static", StaticFiles(directory="static"), name="static")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"], # Allows all origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def get_index():
    return FileResponse('static/index.html')

@app.get("/{whatever:path}")
async def get_static_files_or_404(whatever):
    # try open file for path
    file_path = os.path.join("static",whatever)
    if os.path.isfile(file_path):
        return FileResponse(file_path)
    return FileResponse('static/index.html')

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
    )

class Item(BaseModel):
    name: str
    price: float
    is_offer: Optional[bool] = None

class Values(BaseModel):
    xml: str




@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}


@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_name": item.name, "item_id": item_id}

@app.post("/res/values")
async def res_values(xml: str = Form(...)):
    obj = convertXml2Dict(xml)
    if obj is None:
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="The input isn't suppot")
    else:
        return convertXml2Dict(xml)

if __name__ == "__main__":
    uvicorn.run(app, port=8000)

